package com.example.micrweb.front.controller;

import com.example.common.enums.RCode;
import com.example.common.util.CommonUtil;
import com.example.common.util.JwtUtil;
import com.example.micrweb.front.service.SmsService;
import com.example.micrweb.front.service.impl.RealNameServiceImpl;
import com.example.micrweb.front.view.RespResult;
import com.example.micrweb.front.vo.RealNameVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.example.api.model.Image;
import org.example.api.model.User;
import org.example.api.pojo.UserCenterInfo;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @description: TODO
 * @author: uu
 * @data: 2023/7/14 下午 09:01
 * @version: v1.0
 */
@Tag(name="用户功能")
@RestController
@RequestMapping("/v1/user")
public class UserController extends BaseController{
    @Resource
    private SmsService smsService;
    @Resource
    JwtUtil jwtUtil;
    @Resource
    RealNameServiceImpl realNameService;

    @Operation(summary = "用户上传图片")
    @PostMapping("upload")
    /*用户上传图片*/
    public RespResult userUpFile(@RequestParam("upfile")MultipartFile multipartFile, @RequestHeader("uid") Integer uid){
        RespResult result = RespResult.fail();
        Map<String, Object> info = new HashMap<>();
        if (!multipartFile.isEmpty()){
            info.put("上传文件类型参数", multipartFile.getName());
            info.put("内容类型", multipartFile.getContentType());
            var ext = "unkown";
            var fileName = multipartFile.getOriginalFilename();
            if (fileName.indexOf(".") > 0){
                ext = fileName.substring(fileName.indexOf("."));
            }
            var newFile = UUID.randomUUID() + ext;
            var path = "C:\\Users\\uu\\Desktop\\SpringBoot+Vue\\project\\ylb\\upFile\\" + newFile;
            info.put("上传的文件名名称", path);
            try {
                multipartFile.transferTo(new File(path));
                // 将文件的路径名存到数据库中
                Image image = new Image();
                image.setUid(uid);
                image.setPath(path);
                imageService.userImage(image);
                result.setRCode(RCode.SUCC);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        info.forEach((k,v)->{
            System.out.println(k + "->" + v);
        });
        return result;
    }

    @GetMapping("/getImage")
    @ResponseBody
    /*获取用户头像*/
    public ResponseEntity<byte[]> userImage(@RequestHeader("uid") Integer uid){
        Image image = imageService.queryUserImage(uid);
        byte[] imageBytes  = null;
        if (image != null){
            String path = image.getPath();
//            ClassPathResource resource = new ClassPathResource(path);
            try {
                imageBytes = Files.readAllBytes(Path.of(path));

            } catch (IOException e) {
                throw new RuntimeException("读取图片失败");
            }
        }
        return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG)
                .body(imageBytes);
    }

    @Operation(summary = "用户中心", description = "姓名、手机号、最近登陆时间、可用余额")
    @GetMapping("/center")
    /*个人中心*/
    public RespResult userCenter(@RequestHeader("Uid") Integer id){
        RespResult result = RespResult.fail();
        if (id != null && id > 0){
            UserCenterInfo userCenterInfo = userService.queryUserCenter(id);
            if (userCenterInfo != null){
                result.setRCode(RCode.SUCC);
                result.setData(userCenterInfo);
            }
        }else {
            result.setRCode(RCode.REQUEST_PARAM_ERR);
        }
        return result;
    }


    @Operation(summary = "用户实名认证", description = "验证身份证、姓名、手机号是否一致")
    @PostMapping("/realName")
    /*用户实名认证*/
    public RespResult userRealName(@RequestBody RealNameVO realNameVO){
        RespResult result = RespResult.fail();
        if (CommonUtil.checkPhone(realNameVO.getPhone())){
            // 格式验证
            if (StringUtils.isNotBlank(realNameVO.getName()) &&
                    StringUtils.isNotBlank(realNameVO.getIdCard())){
                // 手机验证码验证
                if (smsService.checkSmsCode(realNameVO.getPhone(),realNameVO.getCode())) {
                    // 是否已经实名认证了
                    User user = userService.queryByPhone(realNameVO.getPhone());
                    if (user != null){
                        // 身份证姓名都存在
                        if (StringUtils.isNotBlank(user.getName()) && StringUtils.isNotBlank(user.getIdCard())){
                            result.setRCode(RCode.REQUEST_REALNAME_EXIST);
                        }else {
                            // 实名认证
                            if (realNameService.handlerRealName(realNameVO.getPhone(),realNameVO.getName(),realNameVO.getIdCard())) {
                                result.setRCode(RCode.SUCC);
                            }else {
                                result.setRCode(RCode.REQUEST_REALNAME_ERR);
                            }
                        }
                    }
                }
            }else {
                result.setRCode(RCode.REQUEST_PARAM_ERR);
            }
        }
        return result;
    }


    @Operation(summary = "实名认证检验", description = "检验用户已经实名认证")
    @GetMapping("/realNameExist")
    /*用户是否已经实名认证*/
    public RespResult RealNameExist(@RequestHeader("uid") Integer id){
        RespResult result = RespResult.fail();
        if (id != null && id > 0){
            Boolean flag = userService.queryUserInfo(id);
            if (flag){
                result.setData(true);
                result.setRCode(RCode.SUCC);
            }
        }
        return result;
    }

    @Operation(summary = "用户登录", description = "用户手机号密码验证，更新最后一次登录时间，返回jwtToken、用户基本信息")
    @PostMapping("/login")
    /* 登录，获取token-jwt */
    public RespResult userLogin(@RequestParam String phone, @RequestParam String pword) throws Exception {
        RespResult result = RespResult.fail();
        if (CommonUtil.checkPhone(phone) && pword != null && pword.length() == 32){
            User user = userService.userLogin(phone, pword);
            if (user !=null){
                // 登录成功, 返回token
                Map<String, Object> data = new HashMap<>();
                data.put("uid",user.getId());
                String jwtToken = jwtUtil.createJwt(data, 60 * 2);

                result.setRCode(RCode.SUCC);
                result.setAccessToken(jwtToken);

                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("uid",user.getId());
                userInfo.put("phone", user.getPhone());
                userInfo.put("name", user.getName());

                result.setData(userInfo);
            }else{
                result.setRCode(RCode.REQUEST_LOGIN_ERR);
            }
        }else {
            result.setRCode(RCode.REQUEST_PARAM_ERR);
        }

        return result;
    }


    @Operation(summary = "用户手机号注册", description = "检查验证码，用户注册，账户注册")
    @PostMapping("/register")
    /*手机号注册用户*/
    public RespResult userRegister(@RequestParam("phone") String phone,
                                   @RequestParam("pword") String pword,
                                   @RequestParam("scode") String code){

        RespResult result = RespResult.fail();

        if (CommonUtil.checkPhone(phone)){
            if (pword != null && pword.length() == 32){
                // 检查短信验证码
                if (code !=null){
                    if (smsService.checkSmsCode(phone, code)) {
                        // 验证啊通过，可以注册用户
                        int registerResult = userService.userRegister(phone, pword);
                        if (registerResult == 1) {
                            result.setRCode(RCode.SUCC);
                        }else if (registerResult == 2){
                            // 手机号已被注册
                            result.setRCode(RCode.REQUEST_PHONE_EXIST);
                        }
                        else {
                            // 注册失败
                            result.setRCode(RCode.REQUEST_PARAM_ERR);
                        }
                    }else {
                        // 验证码错误
                        result.setRCode(RCode.REQUEST_SMS_CODE_ERR);
                    }
                }

            }else {
                result.setRCode(RCode.REQUEST_PARAM_ERR);
            }

        }else {
            result.setRCode(RCode.REQUEST_PHONE_FORMAT_ERR);
        }
        return result;
    }


    @Operation(summary = "手机验证", description = "手机是否被使用")
    @GetMapping("/phone/exists")
    /*手机号是否存在*/
    public RespResult phoneExists(@RequestParam("phone") String phone){
        RespResult result = RespResult.fail();
        // 手机格式验证
        if (CommonUtil.checkPhone(phone)){
            User user = userService.queryByPhone(phone);
            if (user ==null){
                result.setRCode(RCode.SUCC);
            }else {
                result.setRCode(RCode.REQUEST_PHONE_EXIST);

            }
        }else{
            result.setRCode(RCode.REQUEST_PHONE_FORMAT_ERR);
        }
        return result;
    }

}
